﻿// Why is the code so rubbed? It's missing your perfection.
import React from "react";
import { connect } from "react-redux";
import {
  Form,
  Tag,
  Button,
  Table,
  Icon,
  message,
  Row,
  Col,
  Spin,
  Popover,
} from "antd";
import {
  addCalculate,
  currencyPrecisionCal,
  messages,
  queryCurrencyPrecision,
} from "share/common";
import menuRoute from "routes/menuRoute";
import expenseReportService from "containers/expense-report/expense-report.service";
import errorMessage from "share/errorMessage";
import EditPayInfo from "containers/expense-report/template/edit-pay-info";
import SlideFrame from "components/slide-frame";
import Condition from "components/condition";
import WriteOffModal from "containers/expense-report/template/write-off-modal";
import moment from "moment";
const If = Condition.If;

class PayInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      payingBankList: [], //付款行信息
      payInfo: {}, //付款行信息
      columns: [
        {
          title: messages("common.sequence"),
          dataIndex: "sequence",
          width: 48,
          render: (value, record, index) => index + 1,
        },
        {
          title: messages("expense-parent-report.key118") /*付款币种*/,
          dataIndex: "currencyCode",
          width: "10%",
        },
        {
          title: messages("expense-parent-report.key31") /*付款金额*/,
          dataIndex: "amount",
          width: "10%",
          render: (amount, record) => {
            return this.filterMoney(
              amount,
              queryCurrencyPrecision(record.currencyCode),
              false
            );
          },
        },
        {
          title: messages("expense-parent-report.key119") /*核销金额*/,
          dataIndex: "writeOffAmount",
          width: "10%",
          render: (writeOffAmount, record) => {
            return this.filterMoney(
              writeOffAmount,
              queryCurrencyPrecision(record.currencyCode),
              false
            );
          },
        },
        {
          title: (
            <Popover
              content={
                messages("expense-parent-report.key120") /*实际待付款金额*/
              }
            >
              {messages("expense-parent-report.key120") /*实际待付款金额*/}
            </Popover>
          ),
          dataIndex: "realPaymentAmount",
          width: "10%",
          render: (value, record) =>
            this.filterMoney(
              value,
              queryCurrencyPrecision(record.currencyCode),
              false
            ),
        },
        {
          title: messages("expense-parent-report.key121") /*付款对象*/,
          dataIndex: "payeeCode",
          width: "10%",
          render: (index, record) => this.columnPayObject(record),
        },
        {
          title: messages("expense-parent-report.key122") /*收款账号*/,
          dataIndex: "accountNumber",
          width: "20%",
          render: (index, record) => this.columnAccountNumber(record),
        },
        {
          title: messages("expense-parent-report.key198") /*付款属性*/,
          dataIndex: "payArr",
          width: "20%",
          render: (index, record) => this.columnPayAttributes(record),
        },
        {
          title: messages("expense-parent-report.key199") /*计划付款日期*/,
          dataIndex: "planedPaymentDate",
          width: "15%",
          render: (value) => (value ? moment(value).format("YYYY-MM-DD") : "-"),
        },
        {
          title: messages("common.remark") /*备注*/,
          dataIndex: "remark",
          width: "20%",
          render: (value) =>
            value ? <Popover content={value}>{value}</Popover> : "-",
        },
        {
          title: messages("common.operation"),
          dataIndex: "id",
          width: "10%",
          render: (value, record) => {
            return this.props.operateMode === "readOnly" ||
              this.props.profile["app.borrow.disabled"] ? (
              "-"
            ) : (
              <a onClick={() => this.handleWriteOff(record)}>
                {messages("expense-parent-report.key155") /*冲借款*/}
              </a>
            );
          },
        },
      ], //付款列
      loading: true, //加载ing
      showPayingBankModal: false, //显示付款行弹框
      showWriteOff: false, //显示核销弹框
      writeOffParams: {},
    };
    this.loanDetail = menuRoute.getRouteItem("loan-detail"); //借款单 - 借款单详情（公司模式）
    this.loanDetailView = menuRoute.getRouteItem("loan-detail-view"); //借款单查看 - 借款单详情（公司／集团模式）
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.expenseRowIsEdit) {
      this.getList();
      this.props.afterReload();
    }
  }

  //查询付款行信息
  getList = () => {
    let { payingBankList } = this.state;
    let getBanks = () => {
      expenseReportService
        .queryPayingBank(this.props.expenseReportOID)
        .then((res) => {
          payingBankList = res.data;
          console.log("res", res.data);
          if (res.data.length) {
            let repaymentDTOList = [];
            res.data.map((item) => {
              if (item.repaymentDTOList) {
                repaymentDTOList.push(1);
              }
            });
            this.props.handleLineId(
              res.data.map((item) => item.id),
              repaymentDTOList,
              res.data[0].repaymentDTOList && res.data[0].repaymentDTOList.map(item => item.loanBusinessCode)
            );
          } else {
            this.props.handleLineId(undefined);
          }
        })
        .catch((e) => {
          errorMessage(e.response);
        })
        .finally(() => {
          this.setState({ loading: false, payingBankList });
        });
    };
    this.setState({ loading: true, payingBankList: [] }, getBanks);
  };

  //选择费用添加付款行信息
  selectInvoiceAddPayingBank = () => {
    this.setState({
      showPayingBankModal: true,
      payInfo: {
        payeeType: 1002,
      },
    });
  };

  //核销
  handleWriteOff = (record) => {
    const { expenseReportOID, userOid, expenseInfo } = this.props;
    this.setState({
      showWriteOff: true,
      writeOffParams: {
        recordInfo: record,
        companyOID: expenseInfo.docCompanyOID,
        expenseReportOID,
        userOid,
        expenseReportApplicationDTOS:
          expenseInfo.expenseReportApplicationDTOS || [],
        setOfBooksId: expenseInfo.setOfBooksId,
        corporationOID: expenseInfo.corporationOID,
        formCode: expenseInfo.formCode
      },
    });
  };

  //跳转借款申请单
  skipLoadApplication = (info) => {
    const { pageFrom } = this.props;
    if (this.props.tenantMode) {
      //集团模式下
      window.open(
        this.loanDetailView.url
          .replace(":formOID", info.formOID)
          .replace(":loanBillOID", info.loanBillOid)
      );
    } else {
      //公司模式下
      window.open(
        this.loanDetail.url
          .replace(":formOID", info.formOID)
          .replace(":loanBillOID", info.loanBillOid)
      );
    }
  };

  //获取总金额
  getPayingAmount = (attr) => {
    let { payingBankList } = this.state;
    let { expenseInfo } = this.props;
    let attrAmountAll = 0;
    let currencyCode = expenseInfo.currencyCode;
    if (payingBankList.length > 0) {
      payingBankList.map((item) => {
        if (typeof item[attr] === "number") {
          attrAmountAll = addCalculate(attrAmountAll, item[attr]);
        }
        currencyCode = item.currencyCode;
      });
    }
    return currencyPrecisionCal(currencyCode, attrAmountAll);
  };

  //关闭付款行弹框
  closePayingBankModal = () => {
    this.setState({ showPayingBankModal: false });
  };

  //处理保存
  handlePayingBankSave = () => {
    this.props.clearSelectInvoiceOIDs();
    this.getList();
    this.closePayingBankModal();
  };

  //付款对象
  columnPayObject = (record) => {
    let typeName = messages("expense-parent-report.key124"); /*未知*/
    if (record.payeeType === 1002) {
      typeName = messages("expense-parent-report.key114") /*员工*/;
    }
    if (record.payeeType === 1001) {
      typeName = messages("expense-parent-report.key113") /*供应商*/;
    }
    return (
      <div style={{ textAlign: "center" }}>
        <Tag color="black">{typeName}</Tag>
        <br />
        <Popover content={record.payeeName}>{record.payeeName}</Popover>
      </div>
    );
  };

  //收款账号
  columnAccountNumber = (record) => {
    let element = (
      <div>
        <span>
          {messages("expense-parent-report.key125") /*户名*/}:{" "}
          {record.accountName}
        </span>
        <br />
        <span>
          {messages("expense-parent-report.key126") /*账号*/}:{" "}
          {record.accountNumber}
        </span>
      </div>
    );
    return <Popover content={element}>{element}</Popover>;
  };

  columnPayAttributes = (record) => {
    let element = (
      <div>
        <span>
          {messages("expense-parent-report.key196") /*付款方式类型*/}:{" "}
          {record.paymentMethodName}
        </span>
        <br />
        <span>
          {messages("expense-parent-report.key197") /*付款用途*/}:{" "}
          {record.cashTransactionClassDTO &&
            record.cashTransactionClassDTO.description}
        </span>
      </div>
    );
    return <Popover content={element}>{element}</Popover>;
  };
  //列扩展信息
  columnRenderAllExpandedRow = (record) => {
    let relatingApplication = record.repaymentDTOList || [];
    if (relatingApplication.length > 0) {
      return (
        <section>
          {relatingApplication.map((item) => {
            return (
              <Row>
                <a
                  className="link-loan"
                  key={item.id}
                  onClick={() => this.skipLoadApplication(item)}
                >
                  <Icon type="link" style={{ color: "#539AF8" }} />
                  &nbsp;
                  {item.id
                    ? messages("expense-parent-report.key260") /*冲借款单*/
                    : messages("expense-parent-report.key156" /*信用借款单*/)}
                  :&nbsp;
                  {item.loanBusinessCode}
                </a>
              </Row>
            );
          })}
          {this.contractLineExpanded(record)}
        </section>
      );
    } else {
      return this.contractLineExpanded(record);
    }
  };

  renderPopAmount = (params) => {
    return `${params.currency} ${this.filterMoney(
      params.amount,
      queryCurrencyPrecision(params.currency),
      true
    )}`;
  };

  contractLineExpanded = (record) => {
    const { contractLoading } = this.state;
    return record.contractHeaderId ? (
      <Spin spinning={contractLoading}>
        {record.contractAssociatedDTO ? (
          <Row className="contract-pay-expanded" gutter={24}>
            <Col span={2}>
              {messages("expense-parent-report.key200") /*关联合同:*/}
            </Col>
            <Col span={6}>
              <Popover
                placement="topLeft"
                content={record.contractAssociatedDTO.contractName}
              >
                {messages("expense-parent-report.key201") /*合同名称:*/}
                {record.contractAssociatedDTO.contractName}
              </Popover>
            </Col>
            <Col span={5}>
              <Popover content={record.contractAssociatedDTO.contractNumber}>
                {messages("expense-parent-report.key202") /*合同编号:*/}{" "}
                {record.contractAssociatedDTO.contractNumber}
              </Popover>
            </Col>
            <Col span={3}>
              <Popover content={record.contractAssociatedDTO.lineNumber}>
                {messages("expense-parent-report.key203") /*行号:*/}
                {record.contractAssociatedDTO.lineNumber}
              </Popover>
            </Col>
            <Col span={3}>
              <Popover
                content={this.renderPopAmount(record.contractAssociatedDTO)}
              >
                {messages("expense-parent-report.key204") /*金额:*/}
                {this.renderPopAmount(record.contractAssociatedDTO)}
              </Popover>
            </Col>
            <Col span={5}>
              <Popover
                content={moment(record.contractAssociatedDTO.dueDate).format(
                  "YYYY-MM-DD"
                )}
              >
                {messages("expense-parent-report.key205") /*合同付款计划日期:*/}{" "}
                {moment(record.contractAssociatedDTO.dueDate).format(
                  "YYYY-MM-DD"
                )}
              </Popover>
            </Col>
          </Row>
        ) : (
          <Row>
            {messages("expense-parent-report.key206") /*未获取相关合同信息*/}
          </Row>
        )}
      </Spin>
    ) : null;
  };

  renderContractLine = (expanded, record) => {
    if (expanded) {
      this.setState({ contractLoading: true });
      expenseReportService
        .getContractLines(record.id)
        .then((res) => {
          record.contractAssociatedDTO = { ...res.data.contractAssociatedDTO };
        })
        .catch((e) => {
          message.error(e.response.data.message);
        })
        .finally(() => {
          this.setState({ contractLoading: false });
        });
    }
  };
  //获取付款币种金额
  getPayingCurrencyCodeAmount = (attr) => {
    let { expenseInfo } = this.props;
    return (
      <span key={attr}>
        {expenseInfo.currencyCode}&nbsp;{this.getPayingAmount(attr)}
      </span>
    );
  };

  handleClose = (refresh) => {
    this.setState({ showWriteOff: false });
    if (typeof refresh === "boolean" && refresh) {
      this.getList();
      this.props.afterWriteOff();
    }
  };

  render() {
    const {
      selectInvoiceOIDs,
      formInfo,
      pageFrom,
      operateMode,
      expenseReportInvoices,
      userOid,
      expenseInfo,
    } = this.props;
    const {
      columns,
      payingBankList,
      loading,
      showPayingBankModal,
      payInfo,
      showWriteOff,
      writeOffParams,
    } = this.state;
    let tableTitle = (
      <div className={"column-title"}>
        <span>
          {messages("common.number") /*数量*/}:&nbsp;
          <b>
            {payingBankList.length}&nbsp;
            <div className="ant-divider" />
          </b>
        </span>
        <span>
          {messages("expense-parent-report.key129") /*付款金额总计*/}:&nbsp;
          <b>{this.getPayingCurrencyCodeAmount("amount")}&nbsp;</b>
        </span>
        <span>
          {messages("expense-parent-report.key130") /*其中*/}:&nbsp;
          {messages("expense-parent-report.key119") /*核销金额*/}:
          <b>{this.getPayingCurrencyCodeAmount("writeOffAmount")}&nbsp;</b>
          &nbsp;{messages("expense-parent-report.key131") /*实际待支付金额*/}
          :&nbsp;
          <b>{this.getPayingCurrencyCodeAmount("realPaymentAmount")}&nbsp;</b>
        </span>
      </div>
    );
    return (
      <div className={"pay-info"}>
        {/*头部信息*/}
        <div className={"header-title"}>
          {messages("expense-parent-report.key127") /*付款信息*/}
        </div>
        <div style={{ marginBottom: 5 }}>
          <If
            value={
              operateMode !== "readOnly" &&
              pageFrom === "myView" &&
              formInfo["customFormPropertyMap"] &&
              formInfo["customFormPropertyMap"][
                "report.property.pay.multi.lines"
              ] === "true"
            }
          >
            <Button
              type="primary"
              loading={loading}
              disabled={selectInvoiceOIDs.length === 0}
              onClick={this.selectInvoiceAddPayingBank}
            >
              {messages("expense-parent-report.key128") /*选择费用添加付款行*/}
            </Button>
          </If>
        </div>
        <div>
          <Table
            size="middle"
            columns={columns}
            rowKey="id"
            dataSource={payingBankList}
            onExpand={this.renderContractLine}
            title={() => tableTitle}
            expandedRowRender={this.columnRenderAllExpandedRow}
            rowClassName={(record) =>
              (record.repaymentDTOList || []).length > 0 ||
              !!record.contractHeaderId
                ? ""
                : "row-expand-display-none"
            }
            bordered
            pagination={false}
          />
        </div>
        <SlideFrame
          show={showPayingBankModal}
          content={EditPayInfo}
          title={messages("expense-parent-report.key132") /*选择付款对象*/}
          params={{
            payInfo: payInfo,
            onClose: this.closePayingBankModal,
            companyOID: expenseInfo.docCompanyOID,
            selectInvoiceOIDs: selectInvoiceOIDs,
            handleSave: this.handlePayingBankSave,
            userOid: { userOid },
            hasInit: false,
            expenseReportInvoices,
            expenseInfo,
            hasSupplierAdd:
              formInfo["customFormPropertyMap"] &&
              formInfo["customFormPropertyMap"]["reimb.venmasteradd.enable"] ===
                "true",
            contractHeaderId: expenseInfo.contractHeaderId,
            currencyCode: expenseInfo.currencyCode,
            formOID: expenseInfo.formOID,
            visible: showPayingBankModal,
          }}
          hasFooter={false}
          onClose={() => this.setState({ showPayingBankModal: false })}
          width="800px"
        />
        {showWriteOff && (
          <WriteOffModal
            visible={showWriteOff}
            close={this.handleClose}
            recordInfo={writeOffParams.recordInfo}
            expenseReportOID={writeOffParams.expenseReportOID}
            userOid={writeOffParams.userOid}
            expenseReportApplicationDTOS={
              writeOffParams.expenseReportApplicationDTOS
            }
            setOfBooksId={writeOffParams.setOfBooksId}
            corporationOID={writeOffParams.corporationOID}
            companyOID={writeOffParams.companyOID}
            formCode={writeOffParams.formCode}
          />
        )}
      </div>
    );
  }
}

PayInfo.propsType = {
  selectInvoiceOIDs: React.PropTypes.array, //选择费用的OID
  expenseReportOID: React.PropTypes.string, //报销单OID
  operateMode: React.PropTypes.string, //操作模式 readOnly:只读。edit:编辑
  clearSelectInvoiceOIDs: React.PropTypes.func, //清除选择费用
  pageFrom: React.PropTypes.string, //场景来源。myView：自己查看场景；approveView：审批人查看场景 auditView：审核者查看场景
  formInfo: React.PropTypes.object, //表单详情
  expenseRowIsEdit: React.PropTypes.bool, //费用行是否被修改了，若true，则需要重新渲染付款行
  afterReload: React.PropTypes.func, //付款行重新渲染后的回调
  afterWriteOff: React.PropTypes.func, //核销后回调
  userOid: React.PropTypes.string,
  expenseReportInvoices: React.PropTypes.array, //费用行
  handleLineId: React.PropTypes.func, //把列表行回传给父级
  expenseInfo: React.PropTypes.object, //费用详情
};

PayInfo.defaultProps = {
  handleLineId: () => {},
  expenseReportInvoices: [],
};

PayInfo.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
  };
}

const WrappedPayInfo = Form.create()(PayInfo);

export default connect(mapStateToProps)(WrappedPayInfo);
